<template>
  <div class="search-result-view">
    <!-- 搜索框 -->
    <div class="search-header">
      <div class="search-input-container">
          <el-input
            v-model="searchQuery"
            placeholder="搜索视频、用户、直播间..."
            class="search-input"
            suffix-icon="el-icon-search"
            @keyup.enter.native="search"
            clearable
            size="large"
          />
          <el-button 
            type="primary" 
            @click="search" 
            class="search-button"
            size="large"
          >搜索</el-button>
        </div>
      <h1 v-if="searchQuery" class="search-title">搜索结果: <span class="search-keyword">{{ searchQuery }}</span></h1>
      <p v-if="searchQuery && totalResults > 0" class="search-stats">
        找到约 {{ totalResults }} 个相关结果
      </p>
    </div>
    
    <!-- 搜索类型切换 -->
    <div class="search-tabs">
      <div 
        v-for="tab in tabs" 
        :key="tab.key"
        :class="['tab-item', { active: activeTab === tab.key }]"
        @click="activeTab = tab.key"
      >
        {{ tab.label }}
        <span v-if="getTabCount(tab.key)" class="tab-count">({{ getTabCount(tab.key) }})</span>
      </div>
    </div>
    
    <!-- 筛选条件 -->
    <div class="filter-section">
      <div class="sort-options">
        <span class="filter-label">排序方式：</span>
        <el-radio-group v-model="sortBy">
          <el-radio label="relevance">综合排序</el-radio>
          <el-radio label="newest">最新发布</el-radio>
          <el-radio label="mostViewed">最多播放</el-radio>
          <el-radio label="mostLiked">最多点赞</el-radio>
        </el-radio-group>
      </div>
      
      <div class="time-filter">
        <span class="filter-label">时间范围：</span>
        <el-select v-model="timeRange">
          <el-option label="不限" value="all">不限</el-option>
          <el-option label="一天内" value="day">一天内</el-option>
          <el-option label="一周内" value="week">一周内</el-option>
          <el-option label="一个月内" value="month">一个月内</el-option>
          <el-option label="一年内" value="year">一年内</el-option>
        </el-select>
      </div>
      
      <div class="category-filter">
        <span class="filter-label">分区：</span>
        <el-select v-model="selectedCategory">
          <el-option label="全部分区" value="all">全部分区</el-option>
          <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id">{{ category.name }}</el-option>
        </el-select>
      </div>
    </div>
    
    <!-- 搜索结果 -->
    <div class="search-results">
      <!-- 视频搜索结果 -->
      <div v-if="activeTab === 'videos'" class="video-results">
        <div v-if="loading" class="loading-container">
          <el-spinner size="large" />
        </div>
        <div v-else-if="videoResults.length > 0" class="video-list">
          <div v-for="video in videoResults" :key="video.id" class="video-item"
               @click="goToVideo(video.id)">
            <div class="video-cover">
              <img :src="video.coverUrl" :alt="video.title" />
              <span class="video-duration">{{ formatDuration(video.duration) }}</span>
            </div>
            <div class="video-info">
              <h3 class="video-title">{{ video.title }}</h3>
              <div class="video-stats">
                <span class="view-count">{{ formatViewCount(video.views) }}</span>
                <span class="like-count">{{ formatViewCount(video.likes) }}</span>
                <span class="upload-time">{{ formatTimeAgo(video.uploadTime) }}</span>
              </div>
              <div class="video-uploader">
                <img :src="video.uploaderAvatar" :alt="video.uploaderName" class="uploader-avatar" />
                <span class="uploader-name">{{ video.uploaderName }}</span>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="no-results">
          <div v-if="loading" class="loading-content">
            <div class="loading-spinner"><i class="fa fa-spinner fa-spin fa-5x"></i></div>
            <h3>正在搜索中...</h3>
          </div>
          <div v-else class="no-results-content">
            <i class="fa fa-search fa-5x"></i>
            <h3>未找到相关"{{ searchQuery }}"的内容</h3>
            <p>尝试使用其他关键词，或检查拼写是否正确</p>
          </div>
          <!-- 热门搜索推荐 -->
          <div class="hot-searches">
            <h3>热门搜索</h3>
            <div class="hot-search-tags">
              <span 
                v-for="(tag, index) in hotSearchTags" 
                :key="index"
                class="hot-search-tag"
                @click="searchByTag(tag)"
              >
                {{ tag }}
              </span>
            </div>
          </div>
        </div>
      </div>
      <!-- 用户搜索结果 -->
      <div v-if="activeTab === 'users'" class="user-results">
        <div v-if="userResults.length > 0" class="user-list">
          <div v-for="user in userResults" :key="user.id" class="user-item"
               @click="goToUser(user.id)">
            <img :src="user.avatar" :alt="user.username" class="user-avatar" />
            <div class="user-info">
              <div class="username">{{ user.username }}</div>
              <div class="user-bio">{{ user.bio || '暂无简介' }}</div>
              <div class="user-stats">
                <span>{{ formatViewCount(user.followers) }} 粉丝</span>
                <span>{{ user.videos }} 视频</span>
              </div>
            </div>
            <el-button type="primary" size="small" class="follow-btn"
                        :disabled="isFollowing(user.id)"
                        @click.stop="followUser(user.id)">
              {{ isFollowing(user.id) ? '已关注' : '关注' }}
            </el-button>
          </div>
        </div>
        <div v-else class="empty-results">
          <el-empty description="没有找到相关用户" />
        </div>
      </div>
      <!-- 直播间搜索结果 -->
      <div v-if="activeTab === 'live'" class="live-results">
        <div v-if="liveResults.length > 0" class="live-list">
          <div v-for="room in liveResults" :key="room.id" class="live-item"
               @click="goToLive(room.id)">
            <div class="live-cover">
              <img :src="room.cover" :alt="room.title" />
              <div v-if="room.status === 'live'" class="live-badge">
                <span class="live-dot"></span>
                直播中
              </div>
              <span class="viewer-count">{{ formatViewerCount(room.viewers) }}</span>
            </div>
            <div class="live-info">
              <h3 class="live-title">{{ room.title }}</h3>
              <div class="streamer-info">
                <img :src="room.streamer.avatar" :alt="room.streamer.name" class="streamer-avatar" />
                <span class="streamer-name">{{ room.streamer.name }}</span>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="empty-results">
          <el-empty description="没有找到相关直播间" />
        </div>
      </div>
    </div>
    
    <!-- 分页 -->
    <div v-if="totalPages > 1" class="pagination-container">
      <el-pagination
        background
        layout="prev, pager, next, jumper"
        :total="totalResults"
        :page-size="pageSize"
        v-model:current-page="currentPage"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script>
import { searchService } from '../services'

export default {
  name: 'SearchResultView',
  props: {
    keyword: {
      type: String,
      default: ''
    }
  },
  data() {
      return {
        activeTab: 'videos',
        tabs: [
          { key: 'videos', label: '视频', count: 0 },
          { key: 'users', label: '用户', count: 0 },
          { key: 'live', label: '直播', count: 0 }
        ],
        categories: [],
        selectedCategory: 'all',
        sortBy: 'relevance',
        timeRange: 'all',
        videoResults: [],
        userResults: [],
        liveResults: [],
        loading: false,
        currentPage: 1,
        pageSize: 20,
        totalResults: 0,
        totalPages: 0,
        followingUsers: [],
        hotSearchTags: [
          '流浪地球3', '华为Mate70 Pro', '2024音乐节', '夏日动漫新番', 
          '健身达人教学', '数码产品测评', '美食制作教程', '游戏攻略',
          'AI绘画', '编程学习', '旅游攻略', '职场技能'
        ]
    }
  },
  async mounted() {
    // 从URL获取搜索参数
    const query = this.$route.query.q
    if (query) {
      this.searchQuery = query
      await this.search()
    }
    
    // 获取分类列表
    this.fetchCategories()
  },
  watch: {
    activeTab() {
      this.currentPage = 1
      this.performSearch()
    },
    sortBy() {
      this.currentPage = 1
      this.performSearch()
    },
    timeRange() {
      this.currentPage = 1
      this.performSearch()
    },
    selectedCategory() {
      this.currentPage = 1
      this.performSearch()
    }
  },
  computed: {
      searchQuery() {
        // 优先使用路径参数，兼容旧的查询参数形式
        return this.keyword || this.$route.query.q || '';
      },
      // 高亮关键词的方法
      highlightKeyword() {
        return (text) => {
          if (!text || !this.searchQuery) return text;
          const regex = new RegExp(`(${this.searchQuery})`, 'gi');
          return text.replace(regex, '<mark>$1</mark>');
        };
      }
    },
    methods: {
      // 按标签搜索
      searchByTag(tag) {
        // 直接使用路径参数进行搜索
        this.$router.push({ path: `/search/${encodeURIComponent(tag)}` });
      },
      
      // 获取标签计数
      getTabCount(tabKey) {
        switch(tabKey) {
          case 'videos':
            return this.videoResults.length || 0;
          case 'users':
            return this.userResults.length || 0;
          case 'live':
            return this.liveResults.length || 0;
          default:
            return 0;
        }
      },
      
      async search() {
      if (!this.searchQuery.trim()) {
        this.$message.warning('请输入搜索内容')
        return
      }
      
      // 更新URL参数
      this.$router.push({
        path: '/search',
        query: { q: this.searchQuery }
      })
      
      this.currentPage = 1
      await this.performSearch()
    },
    
    async performSearch() {
      // 更新页面标题
      if (this.searchQuery) {
        document.title = `搜索 "${this.searchQuery}" - 视界无界`;
      }
      
      this.loading = true
      try {
        const filters = {
          category: this.selectedCategory === 'all' ? null : this.selectedCategory,
          sortBy: this.sortBy,
          timeRange: this.timeRange,
          page: this.currentPage,
          limit: this.pageSize
        }
        
        if (this.activeTab === 'videos') {
          const results = await searchService.searchVideos(this.searchQuery, filters)
          this.videoResults = results.videos
          this.totalResults = results.total
          this.totalPages = results.totalPages
          // 更新标签计数
          this.updateTabCounts()
        } else if (this.activeTab === 'users') {
          const results = await searchService.searchUsers(this.searchQuery, filters)
          this.userResults = results.users
          this.totalResults = results.total
          this.totalPages = results.totalPages
          // 更新标签计数
          this.updateTabCounts()
        } else if (this.activeTab === 'live') {
          const results = await searchService.searchLiveRooms(this.searchQuery, filters)
          this.liveResults = results.rooms
          this.totalResults = results.total
          this.totalPages = results.totalPages
          // 更新标签计数
          this.updateTabCounts()
        }
      } catch (error) {
        this.$message.error('搜索失败')
      } finally {
        this.loading = false
      }
    },
    
      // 更新所有标签的计数
      updateTabCounts() {
        this.tabs = this.tabs.map(tab => ({
          ...tab,
          count: this.getTabCount(tab.key)
        }));
      },
      
      async fetchCategories() {
      // 获取分类列表（实际项目中从API获取）
      this.categories = [
        { id: 'anime', name: '动画' },
        { id: 'game', name: '游戏' },
        { id: 'music', name: '音乐' },
        { id: 'dance', name: '舞蹈' },
        { id: 'knowledge', name: '知识' },
        { id: 'tech', name: '科技' },
        { id: 'sports', name: '运动' },
        { id: 'car', name: '汽车' },
        { id: 'lifestyle', name: '生活' },
        { id: 'food', name: '美食' }
      ]
    },
    
    handlePageChange(page) {
      this.currentPage = page
      this.performSearch()
    },
    
    goToVideo(videoId) {
      this.$router.push(`/video/${videoId}`)
    },
    
    goToUser(userId) {
      this.$router.push(`/user/${userId}`)
    },
    
    goToLive(roomId) {
      this.$router.push(`/live/${roomId}`)
    },
    
    async followUser(userId) {
      // 模拟关注用户
      this.followingUsers.push(userId)
      this.$message.success('关注成功')
    },
    
    isFollowing(userId) {
      return this.followingUsers.includes(userId)
    },
    
    formatViewCount(count) {
      if (count >= 10000) {
        return (count / 10000).toFixed(1) + '万'
      }
      return count
    },
    
    formatDuration(seconds) {
      const minutes = Math.floor(seconds / 60)
      const secs = seconds % 60
      return `${minutes}:${secs.toString().padStart(2, '0')}`
    },
    
    formatTimeAgo(dateString) {
      const date = new Date(dateString)
      const now = new Date()
      const diff = now - date
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))
      const hours = Math.floor(diff / (1000 * 60 * 60))
      const minutes = Math.floor(diff / (1000 * 60))
      
      if (days > 0) {
        return `${days}天前`
      } else if (hours > 0) {
        return `${hours}小时前`
      } else if (minutes > 0) {
        return `${minutes}分钟前`
      } else {
        return '刚刚'
      }
    }
  }
}
</script>

<style scoped>
.search-result-view {
  min-height: calc(100vh - 200px);
  padding: 40px 0;
  background-color: #f8f9fa;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.search-header {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px 0;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.search-title {
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 15px;
  color: #333;
}

.search-keyword {
  color: #ff4d4f;
  font-weight: 700;
  padding: 0 5px;
  border-bottom: 3px solid #ff4d4f;
}

.search-stats {
  color: #666;
  font-size: 16px;
  margin-bottom: 15px;
  font-weight: 500;
}

.search-input-container {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
  max-width: 700px;
  margin-left: auto;
  margin-right: auto;
  background: white;
  padding: 10px;
  border-radius: 25px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  gap: 0;
}

.search-input-container:hover {
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.search-input {
  width: 500px;
  border-radius: 20px 0 0 20px;
  border-right: none;
}

.search-button {
  border-radius: 0 20px 20px 0;
  min-width: 80px;
  background: #ff4d4f;
  border-color: #ff4d4f;
  transition: all 0.3s ease;
}

.search-button:hover {
  background: #ff7875;
  border-color: #ff7875;
  transform: scale(1.05);
}

.search-tips {
  color: #666;
  font-size: 14px;
}

.search-tabs {
  display: flex;
  background: white;
  border-radius: 12px;
  padding: 0 20px;
  margin-bottom: 30px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  border-bottom: 2px solid #f0f0f0;
  transition: box-shadow 0.3s ease;
}

.search-tabs:hover {
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12);
}

.tab-count {
  color: #ff4d4f;
  font-size: 12px;
  margin-left: 8px;
  font-weight: 600;
  background: #fff2f0;
  padding: 2px 6px;
  border-radius: 10px;
}

.tab-item {
  padding: 15px 30px;
  cursor: pointer;
  font-size: 16px;
  position: relative;
  transition: all 0.3s ease;
  color: #666;
  border-bottom: 3px solid transparent;
}

.tab-item:hover {
  color: #ff4d4f;
  background-color: #fff5f5;
}

.tab-item.active {
  color: #ff4d4f;
  font-weight: 500;
  background-color: #fff5f5;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 15%;
  width: 70%;
  height: 3px;
  background: #ff4d4f;
  border-radius: 3px;
}

.filter-section {
  display: flex;
  gap: 30px;
  background: white;
  border-radius: 12px;
  padding: 15px 20px;
  margin-bottom: 30px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  flex-wrap: wrap;
  transition: box-shadow 0.3s ease;
}

.filter-section:hover {
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12);
}

.filter-label {
  color: #666;
  font-size: 14px;
  margin-right: 10px;
}

.sort-options, .time-filter, .category-filter {
  display: flex;
  align-items: center;
}

.search-results {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  min-height: 400px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.empty-results {
  padding: 80px 0;
}

/* 视频搜索结果样式 */
.video-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

/* 关键词高亮样式 */
:deep(mark) {
  background-color: #fff2e8;
  color: #ff4d4f;
  padding: 0 2px;
  border-radius: 2px;
}

/* 无搜索结果样式 */
.no-results {
  text-align: center;
  padding: 80px 40px;
  color: #999;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  margin-top: 30px;
}

.loading-spinner {
  color: #ff4d4f;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.no-results-content {
  display: inline-block;
}

.no-results i {
  color: #ffccc7;
  margin-bottom: 25px;
  font-size: 60px;
}

.no-results h3 {
  font-size: 24px;
  margin-bottom: 15px;
  color: #666;
  font-weight: 600;
}

.no-results p {
  font-size: 16px;
  line-height: 1.6;
  max-width: 500px;
  margin: 0 auto;
}

/* 热门搜索推荐 */
.hot-searches {
  margin-top: 40px;
  text-align: center;
  background: #fafafa;
  padding: 30px;
  border-radius: 12px;
  border: 1px solid #f0f0f0;
}

.hot-searches h3 {
  color: #333;
  margin-bottom: 20px;
  font-weight: 600;
  font-size: 18px;
}

.hot-search-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  justify-content: center;
  margin-top: 10px;
}

.hot-search-tag {
  padding: 8px 16px;
  background: white;
  border: 1px solid #d9d9d9;
  border-radius: 18px;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.hot-search-tag::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 77, 79, 0.1), transparent);
  transition: all 0.6s ease;
}

.hot-search-tag:hover::before {
  left: 100%;
}

.hot-search-tag:hover {
  color: #ff4d4f;
  border-color: #ff4d4f;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 77, 79, 0.15);
}

.hot-search-tag:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(255, 77, 79, 0.1);
}

.video-item {
  display: flex;
  flex-direction: column;
  gap: 15px;
  cursor: pointer;
  padding: 15px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.video-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.video-cover {
  position: relative;
  width: 220px;
  height: 124px;
  flex-shrink: 0;
}

.video-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.video-duration {
  position: absolute;
  bottom: 8px;
  right: 8px;
  padding: 2px 6px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  font-size: 12px;
  border-radius: 4px;
}

.video-info {
  flex: 1;
  min-width: 0;
}

.video-title {
  font-size: 18px;
  margin-bottom: 10px;
  line-height: 1.4;
}

.video-stats {
  display: flex;
  gap: 20px;
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
}

.video-uploader {
  display: flex;
  align-items: center;
  gap: 8px;
}

.uploader-avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
}

.uploader-name {
  color: #666;
  font-size: 14px;
}

/* 用户搜索结果样式 */
.user-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.user-item {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 15px;
  border-radius: 8px;
  transition: background 0.3s;
  cursor: pointer;
}

.user-item:hover {
  background: #f5f5f5;
}

.user-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  flex-shrink: 0;
}

.user-info {
  flex: 1;
  min-width: 0;
}

.username {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 5px;
}

.user-bio {
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
}

.user-stats {
  display: flex;
  gap: 20px;
  color: #666;
  font-size: 14px;
}

.follow-btn {
  flex-shrink: 0;
}

/* 直播间搜索结果样式 */
.live-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.live-item {
  cursor: pointer;
  transition: transform 0.3s;
}

.live-item:hover {
  transform: translateY(-5px);
}

.live-cover {
  position: relative;
  padding-top: 56.25%;
  margin-bottom: 10px;
}

.live-cover img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.live-badge {
  position: absolute;
  top: 10px;
  left: 10px;
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 4px 8px;
  background: rgba(255, 0, 0, 0.8);
  color: white;
  border-radius: 4px;
  font-size: 12px;
}

.live-dot {
  width: 8px;
  height: 8px;
  background: white;
  border-radius: 50%;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

.viewer-count {
  position: absolute;
  bottom: 10px;
  right: 10px;
  padding: 4px 8px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  border-radius: 4px;
  font-size: 12px;
}

.live-title {
  font-size: 16px;
  margin-bottom: 8px;
  line-height: 1.4;
  height: 48px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.streamer-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.streamer-avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
}

.streamer-name {
  color: #666;
  font-size: 14px;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .search-input {
    width: 300px;
  }
  
  .filter-section {
    flex-direction: column;
    gap: 15px;
  }
  
  .video-item {
    flex-direction: column;
  }
  
  .video-cover {
    width: 100%;
    height: auto;
    padding-top: 56.25%;
  }
}
</style>